package com.raa.core;

import com.raa.log.LoggerProvider;

import java.util.HashMap;
import java.util.function.Function;
import java.util.logging.Logger;

public class ActionTable {

	private static Logger logger = LoggerProvider.provide(ActionTable.class);

	public enum State {
		Success,
		Crash
	}

	private HashMap<Object, Function> functionMap;

	public ActionTable () {
		this.functionMap = new HashMap<>();
	}

	public ActionTable when(Object state, Function<ValidatingInfo, ?> function) {
		this.functionMap.put(state, function);
		return this;
	}

	protected Object happen(ObjectWrapper wrapper, Object state, Object object, Validator validator, Exception e) {
		Function function = this.functionMap.get(state);
		logger.info("校验 [" + wrapper.getValidateId(this, validator) + "] 的结果: [" + state.toString() + "]，调用响应器.");
		if (function == null) {
			logger.info("校验 [" + wrapper.getValidateId(this, validator) + "] 的并未设置 [" + state.toString() + "] 的响应器，直接返回空");
			return null;
		}

		return function.apply(new ValidatingInfo(object, validator, e));
	}

	public static class ValidatingInfo {
		private final Object object;
		private final Validator validator;
		private final Exception e;

		public ValidatingInfo (Object object, Validator validator, Exception e) {
			this.object = object;
			this.validator = validator;
			this.e = e;
		}

		public Object getObject ( ) {
			return object;
		}

		public Validator getValidator ( ) {
			return validator;
		}

		public Exception getE ( ) {
			return e;
		}
	}

}
